-- claim_voucher.lua
-- KEYS[1]: voucher inventory key (voucher:inventory:{voucherId})
-- KEYS[2]: user claimed vouchers key (user:vouchers:{userId})
-- ARGV[1]: voucher code
-- ARGV[2]: user ID
-- ARGV[3]: current timestamp
-- ARGV[4]: voucher start time
-- ARGV[5]: voucher end time

local voucherInventoryKey = KEYS[1]
local userVouchersKey = KEYS[2]
local voucherCode = ARGV[1]
local userId = ARGV[2]
local currentTime = tonumber(ARGV[3])
local startTime = tonumber(ARGV[4])
local endTime = tonumber(ARGV[5])

-- Check if voucher period is valid
if currentTime < startTime then
    return -1  -- Voucher not started yet
end

if currentTime > endTime then
    return -2  -- Voucher expired
end

-- Check if user has already claimed this voucher
local userHasClaimed = redis.call('SISMEMBER', userVouchersKey, voucherCode)
if userHasClaimed == 1 then
    return -3  -- User has already claimed this voucher
end

-- Try to decrement inventory
local currentInventory = redis.call('GET', voucherInventoryKey)
if currentInventory == false then
    return -4  -- Voucher not found in inventory
end

currentInventory = tonumber(currentInventory)
if currentInventory <= 0 then
    return -5  -- Voucher sold out
end

-- Atomically decrement inventory and add user claim
redis.call('DECR', voucherInventoryKey)
redis.call('SADD', userVouchersKey, voucherCode)

-- Set expiration for user vouchers set (optional, for cleanup)
redis.call('EXPIRE', userVouchersKey, 86400 * 365)  -- 1 year

return currentInventory - 1  -- Return remaining inventory